package com.kittyhawks.bksystem.controller;


import com.kittyhawks.bksystem.entity.*;
import com.kittyhawks.bksystem.service.*;
import com.kittyhawks.bksystem.util.*;
import com.kittyhawks.bksystem.weixin.util.WeiXinFinalValue;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @Author Tony
 */
@Api(value="OrderController",tags={"订单操作接口"})
@RestController
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private PhotograRotaService photograRotaService;

    @Autowired
    private ExtraserviceService extraserviceService;

    @Autowired
    private PremiumService premiumService;

    @Autowired
    private UserService userService;

    @Autowired
    private ExtraserviceService extraService;

    /**
     * 摄影师查看订单详情
     * @return
     */
//    @ApiOperation(value = "获取摄影师订单详情",notes = "根据url的id来获取order的详细信息")
////    @GetMapping("/phr/order/detail")
////    public  Order findOrderDetailByPhotoer( String id) {
////        Order order = orderService.findByPhotoer(id);
////        return order;
////    }


    /**
     * 用户查看订单详情
     * @return
     */
//    @ApiOperation(value = "获取用户订单详情",notes = "根据url的id来获取order的详细信息")
//    @GetMapping("/user/order/detail/{id}")
//    public Order findOrderDetailByUser(@PathVariable("id") String id,
//                                                    HttpServletRequest request) {
////        Photographer photographer = (Photographer) WebUtil.getCurrentUser(request);
//        Order order = orderService.findByUser(id);
//        return order;
//    }


    /**
     * 用户查看订单列表
     * @return
     */
//    @ApiOperation(value = "获取用户已完成订单列表")
//    @GetMapping("/user/order/")
//    public List<Order> findFinishedOrderByUser(/**@RequestParam  String userId, **/
//                                                          HttpServletRequest request) {
////        User user = (User) WebUtil.getCurrentUser(request);
////        String id = user.getId();
//        List<Order> orders = orderService.findFinishedOrderByUser("1");
//        return orders;
//    }



    /**
     * 摄影师查看已完成订单列表
     * @return
     */
//    @ApiOperation(value = "获取摄影师已完成订单列表")
//    @GetMapping("/phr/order/finished")
//    public List<Order> findFinishedOrderByPhotoer(/**@RequestParam String photoerId,**/
//                                       HttpServletRequest request) {
////        User user = (User) WebUtil.getCurrentUser(request);
////        String id = user.getId();
//        List<Order> orders = orderService.findFinishedOrderByPhotoer("1");
//        return orders;
//    }


    /**
     * 摄影师查看已完成订单列表
     * @return
     */
//    @ApiOperation(value = "获取摄影师未完成订单列表")
//    @GetMapping("/phr/order/unfinished")
//    public List<Order> findUnfinishedOrderByPhotoer(/**@RequestParam String photoerId,**/
//                                       HttpServletRequest request) {
////        User user = (User) WebUtil.getCurrentUser(request);
////        String id = user.getId();
//        List<Order> orders = orderService.findUnfinishedOrderByPhotoer("1");
//        return orders;
//    }

    /**
     * 摄影师查看今日未完成订单列表
     * @return
     */
    @ApiOperation(value = "获取摄影师今日未完成订单列表")
    @GetMapping("/phr/order/unfinishedtoday")
    public List<Order> findUnfinishedOrderByPhotoerToday(/**@RequestParam String photoerId,**/
                                                   HttpServletRequest request ) {
//        User user = (User) WebUtil.getCurrentUser(request);
//        String id = user.getId();
        List<Order> orders = orderService.findUnfinishedOrderByPhotoerToday("1");
        return orders;
    }

    /**
     * 摄影师查看今日已完成订单列表
     * @return
     */
    @ApiOperation(value = "获取摄影师今日已完成订单列表")
    @GetMapping("/phr/order/finishedtoday")
    public List<Order> findFinishedOrderByPhotoerToday(/**@RequestParam String photerId,**/
                                                   HttpServletRequest request) {
//        User user = (User) WebUtil.getCurrentUser(request);
//        String id = user.getId();
        List<Order> orders = orderService.findFinishedOrderByPhotoerToday("1");
        return orders;
    }


    /**
     * 用户查看available时间
     * @return
     */
    @ApiOperation(value = "用户查看available时间")
    @GetMapping("/user/order/selectTime")
    public Set findAvailableTime() {
        return photograRotaService.findUsableTime();
    }

    /**
     *根据日期查询可用预约时间段
     *@return
     */
    @ApiOperation(value="根据日期得到当天可预约时间段")
    @GetMapping("/user/order/getAvailableBookTime")
    List<Integer> getAvailableBookTime(String bookDay){
        if(bookDay==null||bookDay=="") return null;
        try {
            List<Integer> list = new ArrayList<>();
            return  orderService.getAvailableBookTime(new SimpleDateFormat("yyyy-MM-dd").parse(bookDay));
        } catch (Exception e) {
            e.printStackTrace();
        }
       return null;
    }

    /**
     * 用户查看服务
     * @return
     */
    @ApiOperation(value = "用户查看服务")
    @GetMapping("/user/order/selectService")
    public List findAvailableClothes() {
        return extraserviceService.findAvailableService();
    }


    @ApiOperation(value = "用户添加订单")
    @PostMapping("/user/order/add")
    public JSONResult addOrder(@RequestParam String bookDayString,
                               @RequestParam Integer bookTime,
                               @RequestParam String premiums,
                               @RequestParam String price,
                               @RequestParam Integer femaleNum,
                               @RequestParam Integer maleNum,
                               @RequestParam String mobile,
                               @RequestParam String extraMessage,
                               @RequestParam String userId){
//        User user = (User) WebUtil.getCurrentUser(request);/**从session中获取user **/
//         String userId = user.getId();
        JSONResult jsonResult = photograRotaService.findAvaiablePhotoer(DateUtil.String2Date(bookDayString),bookTime);
        if(jsonResult.getStatus() == Constant.SUCCESS_CODE) {
            String photographerId = (String)jsonResult.getData();
            int photograId = Integer.valueOf(jsonResult.getMessage());
            int totalCount = femaleNum+maleNum;
            String orderId = UUID.randomUUID().toString().replace("-","");
            java.sql.Date bookDay = DateUtil.String2SqlDate(bookDayString);
            jsonResult =  orderService.addOrderByUser(orderId,
                            bookDay,
                            bookTime,
                            userId,
                            photographerId,
                            totalCount,
                            new BigDecimal(price),
                            extraMessage);
                 if(jsonResult.getStatus()==Constant.SUCCESS_CODE){
                     String [] extraServiceArray = premiums.split(";");
                     List<Premium> premiumList = new ArrayList<>();
                     for(String str:extraServiceArray){
                         Premium p = new Premium();
                         p.setId(UUID.randomUUID().toString().replace("-",""));
                         p.setExtra_id(Integer.parseInt(str.split(",")[0]));
                         p.setAmount(Integer.parseInt(str.split(",")[1].trim()));
                         p.setOrderId(orderId);
                         premiumList.add(p);
                     }
                     try {
                         int flag =photograRotaService.pulledOff(photograId);//下架该时段的摄影师
                         System.out.println(flag);
                     }catch (Exception e){
                         jsonResult.setMessage("下架失败"+bookDay);
                     }
                     try {
                         premiumService.insertByUser(premiumList);
                         extraService.useClothes(premiumList);
                     }catch (Exception e) {
                         jsonResult.setMessage("insert 失败"+e);
                         System.out.println(e);
                     }
                     //userService.updateUser(Integer.parseInt(mobile), maleNum, femaleNum, userId);
                 }
            jsonResult.setData(null);
        }
        return jsonResult;
    }

    @ApiOperation(value = "摄影师完成订单")
    @GetMapping("/phr/order/detail/finish")
    public JSONResult finishOrderByPhr(@RequestParam("id") String orderId){
        System.out.println(orderId);
        return orderService.finishOrderByPhr(orderId);
    }

    @ApiOperation(value = "用户取消订单")
    @GetMapping("/user/order/detail/cancel")
    public JSONResult cancelOrderByUser(String id){
        return orderService.cancelOrderByUser(id);
    }


}
